const db = wx.cloud.database()
var status=0
var nickName
var avatarUrl
Page({

  /**
   * 页面的初始数据
   */
  data: {
    photo: '',
    ColorList: [{
      title: '嫣红',
      name: 'red',
      color: '#e54d42'
    },
    {
      title: '桔橙',
      name: 'orange',
      color: '#f37b1d'
    },
    {
      title: '明黄',
      name: 'yellow',
      color: '#fbbd08'
    },
    {
      title: '橄榄',
      name: 'olive',
      color: '#8dc63f'
    },
    {
      title: '森绿',
      name: 'green',
      color: '#3DB578'
    },
    {
      title: '天青',
      name: 'cyan',
      color: '#1cbbb4'
    },
    {
      title: '海蓝',
      name: 'blue',
      color: '#0081ff'
    },
    {
      title: '姹紫',
      name: 'purple',
      color: '#6739b6'
    },
    {
      title: '木槿',
      name: 'mauve',
      color: '#9c26b0'
    },
    {
      title: '桃粉',
      name: 'pink',
      color: '#e03997'
    },
    {
      title: '棕褐',
      name: 'brown',
      color: '#a5673f'
    },
    {
      title: '玄灰',
      name: 'grey',
      color: '#8799a3'
    },
    {
      title: '草灰',
      name: 'gray',
      color: '#aaaaaa'
    },
    {
      title: '墨黑',
      name: 'black',
      color: '#333333'
    },
    {
      title: '雅白',
      name: 'white',
      color: '#ffffff'
    }],
    color: 'gray',
    check_open:true,
    check_secret:false,
    isLogin:0,
    
  },

  checkboxChange(e) {
    console.log('checkbox发生change事件，携带value值为：', e.currentTarget.dataset.id)
    if(e.currentTarget.dataset.id==0){
      status=0
      this.setData({
        check_open:true,
        check_secret:false
      })
    }else{
      status=1
      this.setData({
        check_open:false,
        check_secret:true
      })
    }
    

   
  },
  async  checkString(content){
    wx.cloud.callFunction({
      name:"checkStr",
      data:{
        content:content
      },
      success(res){
        if(res.result.code==300){
         
        }
        return true
      },
      fail(res){
        if(res.result.code==300){

        }
      }
    })
  },
  //表单提交事件
  formSubmit: function (e) {
    var that=this
    if (!e.detail.value.diary) {
      return wx.showToast({
        title: '内容不能为空',
        icon: 'none'
      });
    }

    wx.cloud.callFunction({
      name:"checkStr",
      data:{
        content:e.detail.value.diary
      },
      success(res){
        if(res.result.code==300){
            wx.showToast({
              title: '内容不干净',
              icon: 'none'
            });
        }else{
          
            wx.showLoading({ title: '加载中' })
            if (that.data.photo) {
              wx.cloud.uploadFile({
                cloudPath: 'diary/' + `${Date.now()}-${Math.floor(Math.random(0, 1) * 10000000)}`+that.data.photo.match(/\.[^.]+?$/)[0],
                filePath: that.data.photo,
              }).then(res => {
                that.setData({
                  photo:res.fileID
                })
                that.addDiary(e)
              }).catch(error => {

              })
            }else{
              that.addDiary(e)
            }
        }
      },
      fail(res){
        if(res.result.code==300){
          wx.showToast({
            title: '内容不干净',
            icon: 'none'
          });
        }else{
            
              wx.showLoading({ title: '加载中' })
              if (that.data.photo) {
                wx.cloud.uploadFile({
                  cloudPath: 'diary/' + `${Date.now()}-${Math.floor(Math.random(0, 1) * 10000000)}`+that.data.photo.match(/\.[^.]+?$/)[0],
                  filePath: that.data.photo,
                }).then(res => {
                  that.setData({
                    photo:res.fileID
                  })
                  that.addDiary(e)
                }).catch(error => {

                })
              }else{
                that.addDiary(e)
              }
        }
      }
    })

  
  },

  //写入数据到集合diary中
  addDiary:function(e){

    db.collection('diary').add({
      data: {
        diary: e.detail.value.diary,
        color: this.data.color,
        photo: this.data.photo,
        create_time: new Date(),
        status:status,
        nickName:nickName,
        avatarUrl:avatarUrl
      }
    }).then(res => {
      wx.switchTab({
        url: '../diary/diary'
      })
    }).catch(console.error)
  },

  //弹出和隐藏选择颜色
  showModal(e) {
    this.setData({
      modalName: e.currentTarget.dataset.target
    })
  },
  SetColor(e) {
    this.setData({
      color: e.currentTarget.dataset.color,
      modalName: null
    })
  },
  hideModal(e) {
    this.setData({
      modalName: null
    })
  },

  //选择图片
  ChooseImage() {
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const tempFilePaths = res.tempFilePaths
        this.setData({
          photo: tempFilePaths[0]
        })
      }
    })
  },

  //图片预览
  ViewImage() {
    wx.previewImage({
      urls: [this.data.photo],
      current: this.data.photo
    });
  },

  //图片删除
  DelImg() {
    wx.showModal({
      title: '提示',
      content: '确定要删除这张照片？',
      cancelText: '取消',
      confirmText: '确定',
      success: res => {
        if (res.confirm) {
          this.setData({
            photo: ''
          })
        }
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  onShow: function () {
    var that=this
    wx.getStorage({
      key: 'user',
      success: function(res) {
        nickName = res.data.nickName
        avatarUrl = res.data.avatarUrl
        that.setData({
          isLogin: 1
        })
      }, fail () {
        that.getUserProfile()
      }
    })
  },
   //用户登录授权
   getUserProfile() {
    var that=this
   wx.getUserProfile({
     desc: '用于完善个人资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
     success: (res) => {
      console.log(res.userInfo)
      nickName = res.userInfo.nickName
      avatarUrl = res.userInfo.avatarUrl
      wx.setStorage({
        key: 'user',
        data: res.userInfo,
      })
      that.setData({
        isLogin: 1
      })
     }
   })
 },
 //保存用户信息，暂时没用
  getopenid(e){
    wx.cloud.callFunction({
      name: 'getopenid',//调用云函数获取用户唯一openid
      complete: res => {
        const openid = res.result.openid
      
        db.collection('user').where({
          _openid: openid
        }).get().then(res => {
          //确保数据库只有一份该用户的信息
          if (res.data == "") {
            console.log("授权登录成功")
            this.setData({
              isLogin: 1
            })
            wx.setStorage({
              key: 'user',
              data: '1',
            })
            db.collection('user').add({
              data: {
                nickName: e.nickName,
                avatarUrl: e.avatarUrl,
                time: util.formatTime(new Date()),
              }
            })
          } else {
            console.log("已经登录过不用授权") 
          }
        })
      }
    })
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})